package com.frame.jfinal.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.imgscalr.Scalr;
import org.imgscalr.Scalr.Method;

import net.sf.json.JSONObject;

import com.frame.hander.FileHander;
import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;


/**
 * @author LRC
 * @createDate 2015年6月1日
 * @description 公共请求控制器
 */
public class CommonController extends Controller {
	
	/**
	 * 上传场馆图片操作
	 */
	public void uploadStadiumPicture(){
		UploadFile f = getFile("picture");
		File file = f.getFile();
		String oldName = file.getName();
		String suffix = oldName.substring(oldName.lastIndexOf("."));
		//获得随机文件名并将文件移动到images/original/目录下
		String rName = FileHander.getNewPicName(suffix);
		File dest = new File(rName);
		file.renameTo(dest);
		String fileName = dest.getName();
		JSONObject data= new JSONObject();
		data.put("name", FileHander.originalPicWebPath+"/"+fileName);
		renderJson(data);
	}
	
	/**
	 * 上传新闻图片操作
	 */
	public void uploadNewsPicture(){
		UploadFile f = getFile("picture");
		File file = f.getFile();
		String oldName = file.getName();
		String suffix = oldName.substring(oldName.lastIndexOf("."));
		//获得随机文件名并将文件移动到images/original/目录下
		String rName = FileHander.getNewPicName(suffix);
		File dest = new File(rName);
		file.renameTo(dest);
		String fileName = dest.getName();
		JSONObject data= new JSONObject();
		data.put("name", FileHander.originalPicWebPath+"/"+fileName);
		//将文件存储为三种不同的格式
		FileOutputStream output = null;
		try {
			suffix = suffix.substring(1);
			BufferedImage src = ImageIO.read(dest);
			//将文件转250*170
			BufferedImage middle = Scalr.resize(src,Method.SPEED,250, 170);
			//保存文件
			output = new FileOutputStream(FileHander.webRoot+File.separator+FileHander.middlePicWebPath+File.separator+fileName);
			ImageIO.write(middle, suffix, output);
			output.close();
			//将文件转95*65
			BufferedImage small = Scalr.resize(src,Method.SPEED, 95, 65);
			//保存文件
			output = new FileOutputStream(FileHander.webRoot+File.separator+FileHander.smallPicWebPath+File.separator+fileName);
			ImageIO.write(small, suffix, output);
			output.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(output!=null){
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		renderJson(data);
	}
	
	/**
	 * @updateTeim 2015年6月1日下午11:31:33
	 * @description 跳转到地图定位界面 
	 */
	public void toMapPosition(){
		render("position.html");
	}
}
